﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using YogaStudio.Data;
using YogaStudio.Data.Domain;

namespace YogaStudio.Service.BLL
{
    public class ProductService : IProductService
    {
        private readonly IYogaStudioEntities _db;

        public ProductService()
        {
            _db = new YogaStudioEntities();
        }

        public ProductService(IYogaStudioEntities db)
        {
            _db = db;
        }

        public IQueryable<Product> GetAllProducts()
        {
            return _db.Products;
        }

        public Product GetProductyId(int? productId)
        {
            return _db.Products.Find(productId);
        }

        public IList<Product> GetAvailableProducts()
        {
            return _db.Products.Where(x => x.IsAvailable).ToList();
        }

        public IQueryable<Product> GetAllAvailableProducts()
        {
            return _db.Products.Where(x => x.IsAvailable);
        }

        public IList<Product> GetTopBestSellingProducts(int count)
        {
            var products = from orderitem in _db.OrderItems where orderitem.Product.IsAvailable
                group orderitem by orderitem.Product
                into g
                orderby g.Sum(x => x.Quantity) descending 
                select g.Key;

            return products.Take(count).ToList();
        }

        public IQueryable<Product> GetAllAvailableProducts(string category, string searchString)
        {
            var productsList = _db.Products.Where(x => x.IsAvailable);

            if (!String.IsNullOrEmpty(category) && category != "All")
            {
                productsList = productsList.Where(x => x.Category.CategoryName == category);
            }

            if (!String.IsNullOrEmpty(searchString))
            {
                productsList = productsList.Where(x => x.ProductName.Contains(searchString));
            }
            return productsList;
        }

        public void AddProduct(Product product)
        {
            _db.Products.Add(product);
            _db.SaveChanges();
        }

        public void UpdateProduct(Product product)
        {
            _db.Entry(product).State = EntityState.Modified;
            _db.SaveChanges();
        }

        public void DeleteProduct(Product product)
        {
            _db.Products.Remove(product);
            _db.SaveChanges();
        }

        public void Dispose(bool disposing)
        {
            if (disposing) _db.Dispose();
        }
    }
}